package com.chif.goingplus.interceptor;

import com.chif.goingplus.pojo.Emp;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Component
public class MyInterceptor implements HandlerInterceptor {

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        HttpSession session = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getSession();
        Emp userInfo = (Emp) session.getAttribute("userInfo");
        //System.out.println(userInfo);
        if (userInfo!=null){
            System.out.println(userInfo.getEname()+"登入了,权限为"+userInfo.getPower());
            String requestURI = request.getRequestURI();
            if (requestURI.contains("delete") && userInfo.getPower()>1){
                return false;//不是超级管理员删除数据进行拦截
            }
            if (requestURI.contains("update") && userInfo.getPower()>2){
                return false;//普通管理员管理员修改数据进行拦截
            }
        }
        //System.out.println("：拦截请求uri: " + request.getRequestURI());

        return true;
    }

    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
